<?php
namespace app\index\controller;
use think\Controller;
//use think\cache\driver\Redis;
//use app\common_unit\controller\Unit;
use think\Cache;
use app\index\controller\ApiToken as Wx_api_token;

class JsApi extends Controller
{
    public function _initialize()
    {
        //$this->redis = new Redis();
        //$this->Unit = new Unit();
        $this->Wx_api_token = new Wx_api_token();
    }
    //jsapi
    public function init($html_url){
        $jsapiTicket = Cache::get('wx_jsapi_ticket');
        //$jsapiTicket = $this->redis->get('wx_jsapi_ticket');
        if(empty($jsapiTicket)||!isset($jsapiTicket)){
            //请求获取Access_token
            $access_token=$this->Wx_api_token->getAccess_token();


            //请求微信服务器获取js_api参数
            $post_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$access_token&type=jsapi";

            $result = $this->https_request($post_url,'');
            $result = json_decode($result,true);
            $jsapiTicket = $result['ticket'];

            Cache::set('wx_jsapi_ticket',$jsapiTicket,7100);
            //$this->redis->set('wx_jsapi_ticket',$jsapiTicket,7100);
        }
        $nonceStr = $this->createNonceStr(); //随机字符串
        $timestamp = time();
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$html_url";
        //file_put_contents( "wx_server_re.txt", $string.PHP_EOL, FILE_APPEND);
        $signature = sha1($string);
        /*返回*/
        $Sign['noncestr'] = $nonceStr;
        $Sign['signature'] = $signature;
        $Sign['timestamp'] = $timestamp;
        $Sign['appId'] = config("wx.appid");
        $Sign['html_url']=$html_url;
        $Sign["jsapiTicket"] = $jsapiTicket;
        return $Sign;
    }
    //随机字符串
    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    //授权地址
    public function getOauthRedirect($redirect_url, $state = '', $scope = 'snsapi_base')
    {
        $appid = config('wx.appid');
        $redirect_uri = urlencode($redirect_url);
        $url =  "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope={$scope}&state={$state}#wechat_redirect";
        //header('location:'.$url);
        return $url;
    }

    /**
     * 发送HTTP请求方法
     * @param  string $url    请求URL
     * @param  array  $data   请求参数
     * @param  string $ref
     * @return array  $data   响应数据
     */
    function https_request($url) {
        $curl = curl_init(); // 启动一个CURL会话
        $data = "";
        $ref ="";
        $this_header = array(
            "content-type: application/x-www-form-urlencoded;
         charset=UTF-8"
        );
        curl_setopt($curl, CURLOPT_HTTPHEADER, $this_header);
        $url = urldecode($url);
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_REFERER, $ref);
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        //curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); // Post提交的数据包
        //curl_setopt($curl, CURLOPT_COOKIEFILE, $GLOBALS ['cookie_file']); // 读取上面所储存的Cookie信息
        //curl_setopt($curl, CURLOPT_COOKIEJAR, $GLOBALS['cookie_file']); // 存放Cookie信息的文件名称
        //curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据
    }
}